package com.voltbarn.vbsensors;

import java.util.ArrayList;
import java.util.List;

import com.voltbarn.vbsensors.*;

import android.app.Activity;
import android.app.Application;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.hardware.SensorEvent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class VBSensorMain extends ListActivity {
	private static final int ACTIVITY_CREATE=0;
	private static final int ACTIVITY_EDIT=1;


	private static final int INSERT_ID = Menu.FIRST;
	private static final int DELETE_ID = Menu.FIRST + 1;

	private VbDBAdapter mDbHelper;
	private Cursor mNotesCursor;
	private List<Message> messages;
	private static final String TAG = "MyActivity";

	// Define primary resources we'll use a few places later
    private static final int[] lls = {R.id.sensorOneLout, R.id.sensorTwoLout, R.id.sensorThreeLout,R.id.sensorFourLout,R.id.sensorFiveLout,R.id.sensorSixLout,R.id.sensorSevenLout,R.id.sensorEightLout};
    private static final int[] tvs = {R.id.tView1, R.id.tView2, R.id.tView3,R.id.tView4, R.id.tView5, R.id.tView6, R.id.tView7, R.id.tView8};

    private AndroidSensors sense;

	public Button button;
	/** Called when the activity is first created. */
		
	long sStartTime = 0L;
	private Handler sHandler = new Handler();

	public VbDBAdapter getvbDB() {
		return mDbHelper;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		//setContentView(R.layout.splash);

		Log.i(TAG, "On Create"); 
		
		//Intent myI = new Intent (this, performStartup.class);
		//startActivity(myI);
		sense = new AndroidSensors(this);
		performStartup();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
	        showWeather();
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	private void performStartup() {
						
		//mDbHelper = new VbDBAdapter(this);
		mDbHelper = new VbDBAdapter(getBaseContext());
		mDbHelper.open();
		fillData();
		setContentView(R.layout.main);
		registerForContextMenu(getListView());
		button = (Button)findViewById(R.id.done);
		button.setOnClickListener(mAddListener);
		
		if (mDbHelper.getNumEntries() != 0) {
			setContentView(R.layout.splash);
			int alv = android.R.id.list;
			ListView lv=(ListView)findViewById(alv);
			lv.setVisibility(View.GONE);
	        sHandler.postDelayed(sUpdateWeatherTask, 2000); // Do first auto update in 2 seconds
	        //setContentView(R.layout.weather);
	        //showWeather();
		}
		
	}
	
	private OnClickListener mDetailListener = new OnClickListener()
	{
		public void onClick(View v)
		{
			
			showDetail(v);
		}
	
	};

	private OnClickListener mAddListener = new OnClickListener()
	{
		public void onClick(View v)
		{
			//long id1 = 0;
		    if (sStartTime == 0L) {
		        sStartTime = System.currentTimeMillis();
		        sHandler.removeCallbacks(sUpdateWeatherTask);
		        sHandler.postDelayed(sUpdateWeatherTask, 5000); // Do first auto update in 5 seconds
		    }
			// do something when the button is clicked
			showWeather();
		}

	};
	
	private Runnable sUpdateWeatherTask = new Runnable() {
		   public void run() {
		       final long start = sStartTime;
		       long millis = SystemClock.uptimeMillis() - start;
		       int seconds = (int) (millis / 1000);
		       //int minutes = seconds / 60;
		       seconds     = seconds % 60;

				//Intent myI = new Intent (getBaseContext(), showWeather.class);
				//startActivity(myI);
				showWeather();
		     
		       //sHandler.postAtTime(this,
		               //start + (((minutes * 60) + seconds + 1) * 10000));
		       sHandler.postDelayed(this, 300000); // Update every 5 minutes
		   }
		};

	private void fillData() {
		// Get all of the rows from the database and create the item list
		mNotesCursor = mDbHelper.fetchAllSensors();
		startManagingCursor(mNotesCursor);

		// Create an array to specify the fields we want to display in the list (only TITLE)
		String[] from = new String[]{VbDBAdapter.KEY_SENSORS};

		// and an array of the fields we want to bind those fields to (in this case just text1)
		int[] to = new int[]{R.id.text1};

		// Now create a simple cursor adapter and set it to display
		SimpleCursorAdapter notes =
				new SimpleCursorAdapter(this, R.layout.row, mNotesCursor, from, to);
				new SimpleCursorAdapter(getApplicationContext(), R.layout.row, mNotesCursor, from, to);
		setListAdapter(notes);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		//menu.add(0, INSERT_ID,0, R.string.menu_insert);
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.main_menu, menu);
	    return true;

	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.about:	        
	        return true;
	    case R.id.new_station:
	        createSensor();
	        return true;
	    case R.id.edit_stations:
			setContentView(R.layout.main);
			registerForContextMenu(getListView());
			fillData();
			return true;
	    case R.id.tdetail:
	    	setContentView(R.layout.tdetail);
	    	showWeatherTdetail();
	    	return true;
	    case R.id.station:
	    	Intent i = new Intent(this, StationSwipe.class);
			startActivity(i);
	    	//setContentView(R.layout.station);
	    	//showWeatherTdetail();
	    	return true;
	    case R.id.refresh:
	    	showWeather();
	    	return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch(item.getItemId()) {
		case INSERT_ID:
			createSensor();
			return true;
		}
		return super.onMenuItemSelected(featureId, item);
	}
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.add(0, DELETE_ID, 0, R.string.menu_delete);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch(item.getItemId()) {
		case DELETE_ID:
			AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
			mDbHelper.deleteSensor(info.id);
			fillData();
			return true;
		}
		return super.onContextItemSelected(item);
	}

	private void createSensor() {
		int numSensors = 0;
		if (messages != null)
			numSensors = messages.size();
		if (numSensors < 8) {
			Intent i = new Intent(this, VbEdit.class);
			//Intent i = new Intent(getBaseContext(), VbEdit.class);
			startActivityForResult(i, ACTIVITY_CREATE);
		} else {
			Toast.makeText(getApplicationContext(), "Maximum sensors\nadded", 5000).show();
		}
	
	}
	
	
	private void intToImage(char numberChar, int where) {
		// By trying base 11 here, we allow an "a" value to show a decimal point
		// if the temp is over 100, i.e. 100.
		int numberInt = Character.digit(numberChar, 11);
		if (numberInt < 0 || numberInt > 10) {
			//Log.d("Tutorial", "Invalid number" + numberInt);
		} else {

			int whereArray[] = { R.id.digit11, R.id.digit12, R.id.digit13, R.id.digit14,
								 R.id.digit21, R.id.digit22, R.id.digit23, R.id.digit24,
								 R.id.digit31, R.id.digit32, R.id.digit33, R.id.digit34,
								 R.id.digit41, R.id.digit42, R.id.digit43, R.id.digit44,
								 R.id.digit51, R.id.digit52, R.id.digit53, R.id.digit54,
								 R.id.digit61, R.id.digit62, R.id.digit63, R.id.digit64,
								 R.id.digit71, R.id.digit72, R.id.digit73, R.id.digit74,
								 R.id.digit81, R.id.digit82, R.id.digit83, R.id.digit84
								 }; // viewId
			int images[] = { R.drawable.zero, R.drawable.one, R.drawable.two,
					R.drawable.three, R.drawable.four, R.drawable.five,
					R.drawable.six, R.drawable.seven, R.drawable.eight,
					R.drawable.nine,R.drawable.dot }; // srcId
			ImageView iv = (ImageView)findViewById(whereArray[where]);
			iv.setImageResource(images[numberInt]);
			//remoteView.setImageViewResource(whereArray[where], images[numberInt]);
		}
	}
	
	public class showWeatherBackground extends AsyncTask <Void, Void, Void>{

		//@Override
		protected Void doInBackground(Void... params) {
			showWeather();
			return null;
		}
	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
	  super.onConfigurationChanged(newConfig);
	  setContentView(R.layout.weather);
	  showWeather();
	}
	
	private void add2List(List l, String s) {
		if (s != null)
			l.add(s);
	}

	private void showWeatherTdetail() {
		List<String> titles = new ArrayList<String>(messages.size());

		if (messages == null) {
			Log.e(TAG, "No data, internet connection problem?");
			return;
		}
		for (Message msg : messages){
			add2List(titles,msg.getID());
			add2List(titles,msg.getTemperature());
			add2List(titles,msg.getHumidity());
			add2List(titles,msg.getPressure());
			add2List(titles,msg.getWinds());
			add2List(titles,msg.getRain());
			add2List(titles,msg.getRain24());
		}
		ArrayAdapter<String> adapter = 
	    		new ArrayAdapter<String>(this, R.layout.otherrow,titles);
	    	this.setListAdapter(adapter);
	}
	
	private void showWeather() {
		Context context = getApplicationContext();
		String text = "Getting current weather: ";
		int durationl = Toast.LENGTH_LONG;
		int durations = Toast.LENGTH_SHORT;
		int si = 0;

		Toast toast = Toast.makeText(context, text + sense.getTemp(), durations);
		toast.show();
		
		float myTemp = sense.getTemp();
		if (myTemp != -99) {
			toast = Toast.makeText(context, "MyTemp: " + myTemp, durationl);
			toast.show();
		}
		BaseFeedParser parser;
		
		Cursor cursor = mDbHelper.fetchAllSensors();
		
		setContentView(R.layout.weather);
		// Hide the listview
		ListView lv;
		int alv = android.R.id.list;
		lv=(ListView)findViewById(alv);
		lv.setVisibility(View.GONE);
		
		// Dissappear all the sensors, appear them when they have a value
		LinearLayout ll;
		TextView tv;
	    //int[] lls = {R.id.sensorOneLout, R.id.sensorTwoLout, R.id.sensorThreeLout,R.id.sensorFourLout};
	    //int[] lls = {R.id.sensorOneLout, R.id.sensorTwoLout, R.id.sensorThreeLout,R.id.sensorFourLout,R.id.sensorFiveLout,R.id.sensorSixLout,R.id.sensorSevenLout,R.id.sensorEightLout};
	    //int[] tvs = {R.id.tView1, R.id.tView2, R.id.tView3,R.id.tView4, R.id.tView5, R.id.tView6, R.id.tView7, R.id.tView8};
/*
  		int[][] stv = {{R.id.tView11, R.id.tView12},
 
				   {R.id.tView21, R.id.tView22},
				   {R.id.tView31, R.id.tView32},
				   {R.id.tView41, R.id.tView42}
				  };
		int[][] stv2 = {{R.id.tView51, R.id.tView52},
				   {R.id.tView61, R.id.tView62},
				   {R.id.tView71, R.id.tView72},
				   {R.id.tView81, R.id.tView82}
				  };
*/		
		int[][] stv = {{R.id.tView11, R.id.tView12},
				   {R.id.tView21, R.id.tView22},
				   {R.id.tView31, R.id.tView32},
				   {R.id.tView41, R.id.tView42},
				   {R.id.tView51, R.id.tView52},
				   {R.id.tView61, R.id.tView62},
				   {R.id.tView71, R.id.tView72},
				   {R.id.tView81, R.id.tView82}
				  };

		
		for (int lli : lls) {
			ll=(LinearLayout)findViewById(lli);
			if (ll != null)
			  ll.setVisibility(View.GONE);
		}
		for (int tvi : tvs) {
			tv=(TextView)findViewById(tvi);
			if (tv != null)
			  tv.setVisibility(View.GONE);
		}
		
		
		//ImageView image = (ImageView) findViewById(R.id.imageView2);
		//image.setImageResource(R.drawable.fogday);


		//int id = mDbHelper.getNumEntries();
		int id = cursor.getCount();
		cursor.moveToFirst();
		String station;
		String[] myType = {"", "vbsp", "vbsp", "vbsp", "vbsp", "vbsp", "vbsp", "vbsp", "vbsp"};
		for (int i = 1, stationCount = 0; i <= id; i++, cursor.moveToNext()) {
			station = cursor.getString(1);
			myType[i] = cursor.getString(2);
			if (myType[i].equals("vbsp") ) { // Need to handle WU too
				parser = new BaseFeedParser(getString(R.string.sensorURL) + station + ".xml");
			} else { // We'll assume it's WU
				parser = new BaseFeedParser(getString(R.string.wuURL) + station);
			}
			List<Message> mess = parser.parse();
			
			if (mess.size() == 0) {	
				// Voltbarn web service will return an error, so parse will return null
				Toast.makeText(context, "VB Station not found: " + station, durationl).show();					
			} else if (mess.get(0).getID() == "") {
				// WeatherUnderground will return a full reply, with everything in it zeroed
				  Toast.makeText(context, "WU Station not found: " + station, durationl).show();					
			} else {
				stationCount++;
				if (stationCount == 1) {
					//messages = parser.parse();
					messages = mess;
				} else {
					//messages.addAll(parser.parse());
					messages.addAll(mess);
				}
			}
		} // for

			List<String> titles = new ArrayList<String>(messages.size());
			String myID = "The ID";
			String stemp = "MyTemp";
			String stemp1 = "MyTemp";
			String stemp2 = "MyTemp";
			if (messages == null) {
				Log.e(TAG, "No data, internet connection problem?");
				return;
			}
			for (Message msg : messages){
				/*
				titles.add(msg.getID());
				titles.add(msg.getTemperature());
				titles.add(msg.getHumidity());
				titles.add(msg.getPressure());
				titles.add(msg.getWinds());
				titles.add(msg.getRain());
				titles.add(msg.getRain24());
				*/
				myID = msg.getID();
				stemp = msg.getTemperature();
				int itemp = 0;
				try {
					itemp = Integer.parseInt(stemp);			  
				} catch (NumberFormatException e) {
				}
				stemp1 = msg.getTemp0();
				stemp2 = msg.getTemp1();
			
				//ttemp = Integer.parseInt(msg.getTemperature());
				
					ll=(LinearLayout)findViewById(lls[si]);
					if (ll != null) { // Easy way to figure out the device is showing the fields
						ll.setVisibility(View.VISIBLE);
						// Make sure it gets redrawn
						ll.invalidate();
						// Set up the callback when a detail record is touched
						ll.setOnClickListener(mDetailListener);
						
						//TextView tv1 = (TextView) findViewById(R.id.tView1);
						TextView tv1 = (TextView)findViewById(tvs[si]);
						tv1.setVisibility(View.VISIBLE);
						tv1.invalidate();
						tv1.setText(getString(R.string.stationS) + ": " + myID + " " + myType[si+1]);
						for (int ti = 0; ti <= 3 && ti < stemp.length(); ti++) {
							// We only care about one decimal of accuracy
							if (stemp.charAt(ti) == ' ') 
								if (ti == 3)
									break; // Reached end of token															
							if (stemp.charAt(ti) != '.') {
								intToImage(stemp.charAt(ti), ti + (si * 4));
							}
						}
						// Set the terminating decimal if temp > 100
						if (itemp >= 100) {
							intToImage('a', 3 + (si * 4));
						}
						if (stemp1 != null)
							if (stemp1.length() != 0) {
								TextView tv4 = (TextView) findViewById(stv[si][0]);
								tv4.setText("T0: " + stemp1);
						}
						if (stemp2 != null)
							if (stemp2.length() != 0) {
								TextView tv5 = (TextView) findViewById(stv[si][1]);
								tv5.setText("T1: " + stemp2);
						}
						si++;
					}
			} // for (int i...
		//button = (Button)findViewById(R.id.refreshWeather);
		button.setOnClickListener(mAddListener);
	} // showWeather)
	//}
	
	private void showDetail(View v)
	{
	    //int[] lls = {R.id.sensorOneLout, R.id.sensorTwoLout, R.id.sensorThreeLout,R.id.sensorFourLout,R.id.sensorFiveLout,R.id.sensorSixLout,R.id.sensorSevenLout,R.id.sensorEightLout};
	    //int[] tvs = {R.id.tView1, R.id.tView2, R.id.tView3,R.id.tView4, R.id.tView5, R.id.tView6, R.id.tView7, R.id.tView8};

		int vid = v.getId();
		
		// Shut off auto-weather updating when we're looking at the detail
        sHandler.removeCallbacks(sUpdateWeatherTask);

		
		for (int i = 0; i < lls.length; i++) {
			if (vid == lls[i]) {
				TextView tv1 = (TextView)findViewById(tvs[i]);
				CharSequence scs = tv1.getText();
				String station = scs.toString();
				String[] stationS = station.split("[ ]");
				station = stationS[1];				
				Toast.makeText(getApplicationContext(), "Showing Detail " + station, 5000).show();

				// We've got the station ID we want detail on, make it happen
				setContentView(R.layout.detail);
				
				ListView lv;
				int alv = android.R.id.list;
				lv=(ListView)findViewById(alv);
				lv.setVisibility(View.GONE);
				
				button = (Button)findViewById(R.id.dBackButton);
				button.setOnClickListener(mAddListener);
				
				String myID = "MyId";
				float tempF;
				String tempS;
				for (Message msg : messages){
					myID = msg.getID();
					if (myID.equals(station)) {
						TextView did = (TextView)findViewById(R.id.did);
						TextView dtemp = (TextView)findViewById(R.id.dtemp);
						TextView dhumid = (TextView)findViewById(R.id.dhumid);
						TextView dpress = (TextView)findViewById(R.id.dpress);
						TextView dwind = (TextView)findViewById(R.id.dwind);
						did.setText("Station: " + myID);
						//dtemp.setText("Temp: " + msg.getTemperature());
						//dhumid.setText("Humidity: " + msg.getHumidity());
						//dpress.setText("Pressure: " + msg.getPressure());
						//dwind.setText("Wind: " + msg.getWinds());
						
						//Meter1 - Temp
						//Meter2 - Humid
						//Meter3 - Pressure
						//Meter4 - Wind
						
				        Gauge meter1    = (Gauge) findViewById(R.id.meter1);
				        tempS = msg.getTemperature().toString().replace("F", "");
				        tempF = new Float(tempS);
				        meter1.setLowerTitle(tempS);
						meter1.setValue(tempF);
						
						Gauge meter2 = (Gauge) findViewById(R.id.meter2);
				        String humidS = msg.getHumidity().toString().replace("%", "");
				        float humidF = new Float(humidS);
				        meter2.setLowerTitle(humidS);
						meter2.setValue(humidF);						

						Gauge meter3 = (Gauge) findViewById(R.id.meter3);
				        String pressS = msg.getPressure().toString();
				        float pressF = new Float(pressS);
				        pressF = pressF * 100;
				        meter3.setLowerTitle(pressS);
						meter3.setValue(pressF);
					}
				}
				break;
			}
		} 
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Cursor c = mNotesCursor;
		c.moveToPosition(position);
		Intent i = new Intent(this, VbEdit.class);
		i.putExtra(VbDBAdapter.KEY_ROWID, id);
		i.putExtra(VbDBAdapter.KEY_SENSORS, c.getString(
				c.getColumnIndexOrThrow(VbDBAdapter.KEY_SENSORS)));
		i.putExtra(VbDBAdapter.KEY_STYPE, c.getString(
				c.getColumnIndexOrThrow(VbDBAdapter.KEY_STYPE)));
		startActivityForResult(i, ACTIVITY_EDIT);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		if (intent == null)
			return;
		Bundle extras = intent.getExtras();
		switch(requestCode) {
		case ACTIVITY_CREATE:
			if (extras != null) {
				String title = extras.getString(VbDBAdapter.KEY_SENSORS);
				String sensor = extras.getString(VbDBAdapter.KEY_STYPE);
				if (title.length() != 0) {
					mDbHelper.createSensor(title,sensor);
					fillData();
				}
			}
			break;
		case ACTIVITY_EDIT:
			Long rowId = extras.getLong(VbDBAdapter.KEY_ROWID);
			if (rowId != null) {
				String editTitle = extras.getString(VbDBAdapter.KEY_SENSORS);
				String editSensor = extras.getString(VbDBAdapter.KEY_STYPE);
				mDbHelper.updateSensor(rowId, editTitle, editSensor);
			}
			fillData();
			break;

		}
	}
}
